package _11_整理题目._1_链表指针._环节点;

import org.junit.Test;
import util.ListNode;

/**
 * 给定两个单链表A，B，假设一定含有公共结点，返回第一个公共结点的指针。
 */
public class _02_两个链表的第一个公共结点 {
    
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        while (p1 != p2) {
            if (p1 == null) {
                p1 = pHead2;
            } else {
                p1 = p1.next;
            }
            if (p2 == null) {
                p2 = pHead1;
            } else {
                p2 = p2.next;
            }
        }
        return p1;
    }
    
    @Test
    public void main() {
        Integer[] array1 = {1, 2};
        Integer[] array2 = {7, 8, 9};
        Integer[] array3 = {3, 4, 5, 6};
        ListNode head1 = ListNode.getListFromArray(array1);
        ListNode head2 = ListNode.getListFromArray(array2);
        ListNode head3 = ListNode.getListFromArray(array3);
        head1.next.next = head3;
        head2.next.next.next = head3;
        ListNode.printList(head1);
        ListNode.printList(head2);
        System.out.printf("交叉部分：");
        ListNode.printList(head3);
        ListNode result = FindFirstCommonNode(head1, head2);
        System.out.println(result.val);
    }
}
